package com.jus.player.fragment.home;


import static com.jus.player.api.OkHttpHelper._DATA;
import static com.jus.player.api.OkHttpHelper._RECORD;
import static com.jus.player.api.OkHttpHelper._TOTAL;
import static com.jus.player.config.AppConfig.INT_0;
import static com.jus.player.config.AppConfig.INT_1;
import static com.jus.player.config.AppConfig.KEY_CATEGORY_ID;
import static com.jus.player.util.CommonUtils.showToast;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.fastjson2.JSONObject;
import com.jus.player.R;
import com.jus.player.activity.home.JsPlayerActivity;
import com.jus.player.activity.home.SearchActivity;
import com.jus.player.adapter.home.RecommendAdapter;
import com.jus.player.api.ApiConfig;
import com.jus.player.api.OkHttpHelper;
import com.jus.player.entity.VideoEntity;
import com.jus.player.fragment.BaseFragment;
import com.jus.player.util.CommonUtils;
import com.jus.player.util.Tag;
import com.jus.player.util.Utils;
import com.jus.player.util.cache.PreloadManager;
import com.jus.player.util.cache.ProxyVideoCacheManager;
import com.jus.player.widget.VerticalViewPager;
import com.jus.player.widget.render.PlayerRenderViewFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import xyz.doikki.videocontroller.StandardVideoController;
import xyz.doikki.videoplayer.player.BaseVideoView;
import xyz.doikki.videoplayer.player.VideoView;
import xyz.doikki.videoplayer.util.L;

/**
 * HomeFragment子页面：推荐Fragment
 */
public class SubRecommendFragment extends BaseFragment implements RecommendAdapter.OnItemBtnClickListener {

    private final Long categoryId;
    private final List<VideoEntity> mVideoList = new ArrayList<>();
    /**
     * 当前播放位置
     */
    private int mCurPos;
    private RecommendAdapter adapter;
    private VerticalViewPager mViewPager;
    private PreloadManager mPreloadManager;
    //private PlayerController mController;
    private StandardVideoController mController;
    private VideoView mVideoView;
    /**
     * 是否需要恢复播放
     */
    private boolean needResume;
    //private RefreshLayout refreshLayout;

    private int pageNo = INT_1;
    public int total;
    // 是否正在请求数据
    private boolean loading = false;

    public SubRecommendFragment() {
        this.categoryId = 2L;
    }

    public SubRecommendFragment(Long categoryId) {
        this.categoryId = categoryId;
    }

    public static SubRecommendFragment newInstance(Long categoryId) {
        return new SubRecommendFragment(categoryId);
    }

    // 初始化Handler，它将在主线程上运行
    private final Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                adapter.notifyDataSetChanged();
            } else if (msg.what == 1) {
                adapter.notifyDataSetChanged();
            }
        }
    };


    @Override
    protected int initLayout() {
        return R.layout.fragment_sub_recommend;
    }

    @Override
    protected void initView() {
        setStatusBarTransparent();
        initViewPager();
        initVideoView();
        //设置上拉加载下拉刷新样式
        initFreshLayout();
        mPreloadManager = PreloadManager.getInstance(getContext());
    }

    @Override
    protected void initData() {
        //初始化数据
        getVideoList(categoryId, true);
    }

    @Override
    protected boolean isLazyLoad() {
        return true;
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mVideoView != null) {
            pauseVideo();
        }
        /*if (mPreloadManager != null) {
            mPreloadManager.removeAllPreloadTask();
        }
        ProxyVideoCacheManager.clearAllCache(getActivity());*/
    }



    @Override
    public void onResume() {
        super.onResume();
        if (needResume) {
            mVideoView.resume();
        }
        needResume = false;
    }

    private final Handler pauseHandler = new Handler(Looper.getMainLooper());
    private Runnable pauseRunnable;
    private int retryCount = 0;
    private static final int MAX_RETRY = 20; // 最大重试次数

    private void pauseVideo() {
        // 清理之前的任务
        if (pauseRunnable != null) {
            pauseHandler.removeCallbacks(pauseRunnable);
        }
        if (mVideoView.getCurrentPlayState() == VideoView.STATE_PAUSED) {
            retryCount = 0;
            return;
        }
        needResume = true;
        mVideoView.pause();

        // 增加重试机制 缩短延迟时间但增加重试
        // 设置延迟检查
        pauseRunnable = () -> {
            if (retryCount++ < MAX_RETRY) {
                pauseVideo();
            } else {
                retryCount = 0; // 达到最大重试次数后重置
            }
        };
        pauseHandler.postDelayed(pauseRunnable, 500);
    }

    /**
     * 初始化视频播放页面
     */
    private void initViewPager() {

        //设置预加载页面数量
        mViewPager = findViewById(R.id.vertical_view_pager);
        mViewPager.setOffscreenPageLimit(2);
        adapter = new RecommendAdapter(getActivity(), this);
        adapter.setVideoList(mVideoList);
        mViewPager.setAdapter(adapter);
        mViewPager.setOverScrollMode(View.OVER_SCROLL_NEVER);
        //注册监听器，监听页面变化事件：滑动，选中...
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            private int mCurItem;
            /**
             * VerticalViewPager是否反向滑动
             */
            private boolean mIsReverseScroll;

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
                if (position == mCurItem) {
                    return;
                }
                mIsReverseScroll = position < mCurItem;
            }

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                // 仅预加载相邻1个视频

                if (position == mCurPos) return;
                // 到底部后加载下页数据，获取ViewPager的总页面数
                int totalPages = mViewPager.getAdapter().getCount();
                // 判断当前页面是否是最后一页
                if (position == totalPages - 1) {
                    // 判断是否还有下一页数据
                    if (pageNo * ApiConfig.PAGE_30_SIZE >= SubRecommendFragment.this.total) {
                        showToast(requireActivity(), "数据加载完毕!");
                    } else if (!loading) {
                        // 数据在请求中，直接关闭
                        pageNo++;
                        getVideoList(categoryId, false);
                    }
                }
                // 仅预加载相邻1个视频
                mPreloadManager.removeAllPreloadTask();
                if (position < mVideoList.size() - 1) {
                    mPreloadManager.addPreloadTask(mVideoList.get(position + 1).getTvDownloadUrl(), position + 1);
                }
                startPlay(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
                if (state == VerticalViewPager.SCROLL_STATE_DRAGGING) {
                    mCurItem = mViewPager.getCurrentItem();
                }
                if (state == VerticalViewPager.SCROLL_STATE_IDLE) {
                    mPreloadManager.resumePreload(mCurPos, mIsReverseScroll);
                } else {
                    mPreloadManager.pausePreload(mCurPos, mIsReverseScroll);
                }
            }
        });
    }

    /**
     * 初始化视频页面
     */
    private void initVideoView() {
        mVideoView = new VideoView(requireContext());
        mVideoView.setLooping(false);
        //以下只能二选一，看你的需求
        mVideoView.setRenderViewFactory(PlayerRenderViewFactory.create());
        //mVideoView.setScreenScaleType(VideoView.SCREEN_SCALE_CENTER_CROP);
        mController = new StandardVideoController(requireContext());
        //mController.addDefaultControlComponent("进度条", false);
        mVideoView.setVideoController(mController);
        mVideoView.setOnStateChangeListener(new BaseVideoView.OnStateChangeListener() {
            @Override
            public void onPlayerStateChanged(int playerState) {
            }

            @Override
            public void onPlayStateChanged(int playState) {
                if (playState == BaseVideoView.STATE_PLAYBACK_COMPLETED) {
                    if (mCurPos + 1 > mVideoList.size() - 1) {
                        showToast(requireActivity(), "已经是最后一条");
                    } else {
                        mViewPager.setCurrentItem(mCurPos + 1, true);
                    }
                }
            }
        });
    }

    private void initFreshLayout() {
        //设置上拉加载下拉刷新样式
       /* refreshLayout = findViewById(R.id.refresh_layout);
        refreshLayout.setOnRefreshListener(refresh -> {
            // 执行数据加载的逻辑
            pageNo = 1;
            loading = false;
            mVideoList.clear();
            getVideoList(categoryId, true);
            // 数据加载完成后，停止刷新动画
            refreshLayout.finishRefresh(true);
        });*/
    }

    /**
     * 请求网络数据：推荐视频列表
     * * @param categoryId 分类ID
     */
    private void getVideoList(Long categoryId, boolean first) {
        if (loading || !isAdded()) return;
        loading = true;
        CommonUtils.showLoading(requireActivity());
        Map<String, String> map = new HashMap<>();
        map.put("pageNo", pageNo + "");
        map.put("pageSize", ApiConfig.PAGE_30_SIZE + "");
        map.put("categoryId", categoryId + "");

        OkHttpHelper.getInstance(requireActivity()).getAsync(ApiConfig.VIDEO_LIST, map,
                new OkHttpHelper.HttpCallback() {
                    @Override
                    public void onSuccess(String response) {
                        if (!isAdded()) return;

                        requireActivity().runOnUiThread(() -> {
                            CommonUtils.hideLoading(requireActivity());
                            try {
                                JSONObject jo = JSONObject.parseObject(response);
                                JSONObject pageJo = jo.getJSONObject(_DATA);
                                total = pageJo.getIntValue(_TOTAL);
                                List<VideoEntity> resList = pageJo.getList(_RECORD, VideoEntity.class);

                                // 暂停播放
                                if (mVideoView != null && mVideoView.isPlaying()) {
                                    mVideoView.pause();
                                }
                                // 更新数据
                                if (first) {
                                    mVideoList.clear();
                                }
                                // 更新数据
                                mVideoList.addAll(resList);
                                adapter.setVideoList(mVideoList);
                                mViewPager.setCurrentItem(INT_0, false);
                                // 延迟确保视图已更新
                                mViewPager.postDelayed(() -> {
                                    if (isAdded() && !requireActivity().isFinishing()) {
                                        startPlay(INT_0);
                                    }
                                }, 300);
                            } catch (Exception e) {
                                showToast(requireActivity(), "数据解析失败");
                            } finally {
                                loading = false;
                                CommonUtils.hideLoading(requireActivity());
                            }
                        });

                    }

                    @Override
                    public void onFailure(OkHttpHelper.HttpException e) {
                        if (!isAdded()) return;
                        requireActivity().runOnUiThread(() -> {
                            CommonUtils.hideLoading(requireActivity());
                            CommonUtils.showToastAsync(requireActivity(), e.getMessage());
                        });
                    }
                });
        loading = false;
    }

    /**
     * 视频播放函数
     *
     * @param position 开始位置
     */
    private void startPlay(int position) {
        if (!isAdded() || isDetached() || getActivity() == null || getActivity().isFinishing()) {
            return;
        }
        // 加强安全校验
        if (position < 0 || position >= mVideoList.size() || mVideoList.get(position) == null) {
            return;
        }
        // 限制重试次数
        final int maxRetry = 3;
        final int[] retryCount = {0};

        Runnable playRunnable = new Runnable() {
            @Override
            public void run() {
                if (retryCount[0]++ >= maxRetry) {
                    L.e("重试 " + maxRetry + " 次后，播放错误");
                    return;
                }
                View itemView = adapter.getViewByPosition(position);
                if (itemView == null || itemView.getTag() == null) {
                    mViewPager.postDelayed(this, 200);
                    return;
                }
                try {
                    RecommendAdapter.ViewHolder viewHolder = (RecommendAdapter.ViewHolder) itemView.getTag();
                    if (viewHolder.mPosition != position) {
                        mViewPager.postDelayed(this, 200);
                        return;
                    }
                    // 播放逻辑
                    mVideoView.release();
                    Utils.removeViewFormParent(mVideoView);
                    VideoEntity videoEntity = mVideoList.get(position);
                    String playUrl = mPreloadManager.getPlayUrl(videoEntity.getTvDownloadUrl());

                    mVideoView.setUrl(playUrl);
                    mController.addControlComponent(viewHolder.mPlayerView, true);
                    viewHolder.mPlayerContainer.addView(mVideoView, 0);
                    getVideoViewManager().add(mVideoView, categoryId == 1L ? Tag.HOT : Tag.RECOMMEND);
                    mVideoView.start();
                    mCurPos = position;
                } catch (Exception e) {
                    L.e("Play error: " + e.getMessage());
                    mViewPager.postDelayed(this, 200);
                }
            }
        };
        mViewPager.post(playRunnable);
    }

    /**
     * 保存播放进度
     *
     * @param outState
     */
    // 保存播放进度
    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mVideoView != null) {
            outState.putLong("progress", mVideoView.getCurrentPosition());
            outState.putInt("position", mCurPos);
        }
    }

    // 恢复播放状态
    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
        if (savedInstanceState != null) {
            long progress = savedInstanceState.getLong("progress", -1);
            int position = savedInstanceState.getInt("position", 0);
            if (progress > 0) {
                mViewPager.setCurrentItem(position);
                mVideoView.seekTo(progress);
            }
        }
    }

    /**
     * 处理adapter里item的点击事件:下一集
     *
     * @param tvId 剧集ID
     */
    @Override
    public void onNextEpisodeClick(Long tvId) {
        JsPlayerActivity.start(getContext(), INT_1, tvId, false);
    }

    /**
     * 处理adapter里item的点击事件:展示选集弹窗
     *
     * @param item 剧集信息
     */
    @Override
    public void onShowEpisodesClick(VideoEntity item) {
        JsPlayerActivity.start(requireActivity(), INT_0, item.getId(), false);
    }

    @Override
    public void onSearchVideoClick(VideoEntity item) {
        Intent i = new Intent(getActivity(), SearchActivity.class);
        i.putExtra(KEY_CATEGORY_ID, categoryId);
        startActivity(i);
        //navigateTo(SearchActivity.class);
    }

}